<?php
// 详细调试脚本

echo "详细调试开始...\n";

// 数据库配置
$dbname = 'yingyang';
$username = 'root';
$password = 'root';

try {
    $pdo = new PDO("mysql:host=127.0.0.1;dbname={$dbname};charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 获取未处理的菜品
    $stmt = $pdo->prepare("SELECT id, name FROM fa_food_dish WHERE ai_called = 0 LIMIT 1");
    $stmt->execute();
    $dishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($dishes)) {
        echo "没有未处理的菜品\n";
        exit;
    }
    
    echo "处理菜品: " . $dishes[0]['name'] . " (ID: " . $dishes[0]['id'] . ")\n\n";
    
    // 模拟API调用过程
    $dishNames = [$dishes[0]['name']];
    $dishList = implode("、", $dishNames);
    
    echo "构造的提示词:\n";
    $prompt = "菜品名称列表：{$dishList}\n\n请根据这些菜品名称，为每个菜品提供以下信息：\n";
    $prompt .= "1. 所需食材列表（包括食材名称和建议用量）\n";
    $prompt .= "2. 烹饪时长（以分钟为单位）\n";
    $prompt .= "3. 制作步骤（详细步骤）\n\n";
    $prompt .= "请严格按照以下JSON格式返回结果，不要包含其他内容：\n";
    $prompt .= "{\n";
    $prompt .= "  \"{$dishList}\": {\n";
    $prompt .= "    \"ingredients\": [\n";
    $prompt .= "      {\"name\": \"鸡蛋\", \"quantity\": \"150克\"},\n";
    $prompt .= "      {\"name\": \"西红柿\", \"quantity\": \"300克\"}\n";
    $prompt .= "    ],\n";
    $prompt .= "    \"cook_time\": \"7分钟\",\n";
    $prompt .= "    \"steps\": \"1. 热锅凉油...\\n2. ...\"\n";
    $prompt .= "  }\n";
    $prompt .= "}";
    
    echo $prompt . "\n\n";
    
    // 调用API
    $apiKey = 'sk-416b931b781c420c9f6331b7346962b5';
    $apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
    $model = 'qwen-plus';
    
    $data = [
        'model' => $model,
        'messages' => [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ],
        'temperature' => 0.1,
        'max_tokens' => 2000
    ];
    
    echo "调用API...\n";
    $headers = [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    
    echo "HTTP状态码: " . $httpCode . "\n";
    echo "CURL错误: " . $error . "\n";
    
    if ($response) {
        echo "响应长度: " . strlen($response) . " 字符\n";
        // 只显示前500个字符以避免输出过长
        echo "响应内容(前500字符): " . substr($response, 0, 500) . "...\n";
        
        $responseArr = json_decode($response, true);
        if ($responseArr) {
            echo "JSON解析成功\n";
            if (isset($responseArr['choices'][0]['message']['content'])) {
                $content = $responseArr['choices'][0]['message']['content'];
                echo "内容长度: " . strlen($content) . " 字符\n";
                echo "内容(前200字符): " . substr($content, 0, 200) . "...\n";
            } else {
                echo "响应格式不符合预期\n";
                print_r(array_keys($responseArr));
            }
        } else {
            echo "JSON解析失败\n";
        }
    } else {
        echo "无响应内容\n";
    }
    
    curl_close($ch);
    
} catch (\Exception $e) {
    echo "错误: " . $e->getMessage() . "\n";
}

echo "\n调试完成\n";
?>